/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.rate.gift.service.impl;

import org.springblade.common.enums.rate.*;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.modules.rate.gift.entity.Gift;
import org.springblade.modules.rate.gift.entity.GiftExchange;
import org.springblade.modules.rate.gift.service.IGiftService;
import org.springblade.modules.rate.gift.vo.GiftExchangeVO;
import org.springblade.modules.rate.gift.mapper.GiftExchangeMapper;
import org.springblade.modules.rate.gift.service.IGiftExchangeService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.rate.gift.vo.exchange.GiftExchangeOperationVO;
import org.springblade.modules.rate.point.entity.PointRecord;
import org.springblade.modules.rate.point.service.IPointRecordService;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 礼物兑换表 服务实现类
 *
 * @author Blade
 * @since 2021-09-20
 */
@Service
public class GiftExchangeServiceImpl extends BaseServiceImpl<GiftExchangeMapper, GiftExchange> implements IGiftExchangeService {


	@Autowired
	private IGiftService giftService;
	@Autowired
	private IPointRecordService pointRecordService;
	@Autowired
	private IUserService userService;
	@Autowired
	private ITenantService tenantService;
	@Override
	public IPage<GiftExchangeVO> selectGiftExchangePage(IPage<GiftExchangeVO> page, GiftExchangeVO giftExchange) {
		return page.setRecords(baseMapper.selectGiftExchangePage(page, giftExchange));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean operation(GiftExchangeOperationVO applyVO) {
		try {
			boolean leaderFlag = false;
			BladeUser authUser = AuthUtil.getUser();
			User user = userService.getById(authUser.getUserId());
			if (user.getLeaderFlag()== YesNoEnum.YES.getKey()) {
				leaderFlag = true;
			}
			if (user.getStatus().equals(UserStatusEnum.LOCK.getKey())) {
				throw new ServiceException("用户处于封锁状态，不能操作");
			}
			if (leaderFlag) {
				throw new ServiceException("用户为领导角色，不可以申请/取消礼品");
			}

			User exchangeUser = userService.getById(user.getId());
			//礼物ID
			Gift giftQ = new Gift();
			giftQ.setCode(applyVO.getGiftCode());
			Gift gift = giftService.getOne(Condition.getQueryWrapper(giftQ).last("limit 1"));

			//积分更新
			if (applyVO.getOperation()!=null && applyVO.getOperation().equals(1) && gift.getNumber() <= 0){
				throw new ServiceException("申请失败，礼物数量不够");
			}
			//更新
			GiftExchange giftExchangeQ = new GiftExchange();
			giftExchangeQ.setGiftCode(applyVO.getGiftCode());
			giftExchangeQ.setMemberId(user.getId());
			GiftExchange oneExchange = this.getOne(Condition.getQueryWrapper(giftExchangeQ).last("limit 1"));
			if (oneExchange==null){
				oneExchange = new GiftExchange();
				BeanUtil.copyNonNull(applyVO,oneExchange);
				oneExchange.setCode("EXCHANGE" + CommonUtil.getTimeString());
			}
			oneExchange.setPoint(gift.getPoint());
			oneExchange.setName(gift.getName());
			oneExchange.setStatus(applyVO.getOperation());
			oneExchange.setMemberName(exchangeUser.getRealName());
			oneExchange.setMemberId(exchangeUser.getId());
			oneExchange.setMediaUrl(gift.getMediaUrl());
			this.saveOrUpdate(oneExchange);
			//礼物比例分

			if (gift.getSelfPoint()!=null){
				exchangeUser.setSelfPoint(exchangeUser.getSelfPoint()-gift.getSelfPoint());
				if (exchangeUser.getSelfPoint()<0) {
					throw new ServiceException("兑换失败，自我表现分不够");
				}
			}
			if (gift.getMatePoint()!=null){
				exchangeUser.setMatePoint(exchangeUser.getMatePoint()-gift.getMatePoint());
				if (exchangeUser.getMatePoint()<0) {
					throw new ServiceException("兑换失败，同事赞赏分不够");
				}
			}
			if (gift.getLeaderPoint()!=null){
				exchangeUser.setLeaderPoint(exchangeUser.getLeaderPoint()-gift.getLeaderPoint());
				if (exchangeUser.getLeaderPoint()<0) {
					throw new ServiceException("兑换失败，领导表扬分不够");
				}
			}


		}catch (Exception e){
			throw new ServiceException(e.getMessage());
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean submit(GiftExchange giftExchange) {
		try {


			boolean leaderFlag = false;
			BladeUser authUser = AuthUtil.getUser();
			User user = userService.getById(authUser.getUserId());
			if (user.getLeaderFlag()==YesNoEnum.YES.getKey()) {
				leaderFlag = true;
			}
			if (giftExchange.getStatus().equals(GiftExchangeStatusEnum.DEAL.getKey())) {
				this.exchangeDeal(giftExchange,user);
			}else if (giftExchange.getStatus().equals(GiftExchangeStatusEnum.CANCEL.getKey())) {
				this.exchangeReturn(giftExchange,user);
			}
			this.saveOrUpdate(giftExchange);

		}catch (Exception e){
			throw new ServiceException(e.getMessage());
		}
		return true;
	}

	/**
	 * 兑换
	 */
	@Transactional(rollbackFor = Exception.class)
	void exchangeDeal(GiftExchange giftExchange, User user){

		//礼物更新
		Gift giftQ = new Gift();
		giftQ.setCode(giftExchange.getGiftCode());
		Gift gift = giftService.getOne(Condition.getQueryWrapper(giftQ).last("limit 1"));
		gift.setNumber(gift.getNumber()-giftExchange.getNumber());
		giftService.updateById(gift);

		User exchangeUser = userService.getById(giftExchange.getMemberId());

		//积分更新
		if (gift.getNumber() <= 0){
			throw new ServiceException("兑换失败，礼物数量不够");
		}

		//礼物比例分
		if (gift.getSelfPoint()!=null){
			exchangeUser.setSelfPoint(exchangeUser.getSelfPoint()-gift.getSelfPoint());
			if (exchangeUser.getSelfPoint()<0) {
				throw new ServiceException("兑换失败，自我表现分不够");
			}

		}
		if (gift.getMatePoint()!=null){
			exchangeUser.setMatePoint(exchangeUser.getMatePoint()-gift.getMatePoint());
			if (exchangeUser.getMatePoint()<0) {
				throw new ServiceException("兑换失败，同事赞赏分不够");
			}
		}
		if (gift.getLeaderPoint()!=null){
			exchangeUser.setLeaderPoint(exchangeUser.getLeaderPoint()-gift.getLeaderPoint());
			if (exchangeUser.getLeaderPoint()<0) {
				throw new ServiceException("兑换失败，领导表扬分不够");
			}
		}
		//用户额度更新
		userService.updateById(exchangeUser);

		PointRecord pointRecord = new PointRecord();
		pointRecord.setName(PointTypeEnum.EXCHANGE.getKeyword());
		pointRecord.setType(PointTypeEnum.EXCHANGE.getKey());
		pointRecord.setPoint(-gift.getPoint());
		pointRecord.setGiftCode(gift.getCode());
		pointRecord.setMemberId(exchangeUser.getId());
		pointRecord.setMemberName(exchangeUser.getRealName());
		pointRecordService.exchangeGift(pointRecord);
	}
	/**
	 * 退货
	 */
	@Transactional(rollbackFor = Exception.class)
	void exchangeReturn(GiftExchange giftExchange, User user){
		User exchangeUser = userService.getById(giftExchange.getMemberId());

		//礼物更新
		Gift giftQ = new Gift();
		giftQ.setCode(giftExchange.getGiftCode());
		Gift gift = giftService.getOne(Condition.getQueryWrapper(giftQ).last("limit 1"));
		Integer number = gift.getNumber();
		number += giftExchange.getNumber();
		gift.setNumber(number);
		giftService.updateById(gift);

		//积分更新
		PointRecord pointRecord = new PointRecord();
		//租户
		User operationUser = userService.getById(user.getId());
		Tenant tenant = tenantService.getByTenantId(operationUser.getTenantId());
		String[] pointRatio = tenant.getGiftPointRatio().split(":");
		for (int i = 0; i < pointRatio.length; i++) {
			String point = pointRatio[i];
			Double percent = Integer.parseInt(point) * 0.1;
			BigDecimal percentPoint = new BigDecimal(gift.getPoint()*percent);
			if (i==0){
				pointRecord.setSelfPoint(percentPoint);
				exchangeUser.setSelfPoint(exchangeUser.getSelfPoint()+percentPoint.intValue());

			}else if (i==1){
				pointRecord.setMatePoint(percentPoint);
				exchangeUser.setMatePoint(exchangeUser.getMatePoint()+percentPoint.intValue());

			}else {
				pointRecord.setLeaderPoint(percentPoint);
				exchangeUser.setLeaderPoint(exchangeUser.getLeaderPoint()+percentPoint.intValue());

			}
		}
		pointRecord.setName(PointTypeEnum.RETURN.getKeyword());
		pointRecord.setType(PointTypeEnum.RETURN.getKey());
		pointRecord.setPoint(gift.getPoint());
		pointRecord.setGiftCode(gift.getCode());

		pointRecord.setMemberId(exchangeUser.getId());
		pointRecord.setMemberName(exchangeUser.getRealName());
		pointRecordService.exchangeGift(pointRecord);
		//用户额度更新
		userService.updateById(exchangeUser);

	}

}
